package com.sketch.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.sketch.commom.CodeMsg;
import com.sketch.commom.Result;
import com.sketch.commom.annotation.UserStatus;
import com.sketch.commom.utils.HttpUtil;
import com.sketch.entity.SysUser;
import com.sketch.entity.WebUser;
import com.sketch.service.SystemUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@Api(tags = "用户管理 API")
@RequestMapping(value = "/api/webUser")
@Slf4j
public class SystemUserController {
    @Resource
    private SystemUserService systemUserService;

//    @UserStatus(isLogin = false)
//    @ApiOperation("登录")
//    @GetMapping("/login")
//    public Result login(@RequestParam("name") String name, @RequestParam("password") String password) {
//        return systemUserService.login(name,password);
//    }

    /**
     * 微信登录，第一次登录就注册（方案一，可先填写邀请人，如果无则跳过，二，先注册，然后再手动填写邀请人）
     */
    @ApiOperation("微信登录")
    @PostMapping("/wechatLogin")
    public Result<SaTokenInfo> wechatLogin(@RequestParam @ApiParam(value = "微信code") String code, @ApiParam(value = "用户的邀请码") String iCode) throws Exception {
        if (ObjectUtil.isNull(code)) {
//            return new AppBack(-1, "code不能为空");
            return Result.error(CodeMsg.FAIL);
        }
        String wechatAppId = "wxf206ffce8f3e2b61";
        String wechatSecret = "0487d2ef4b500b9d368cf6501d2836a7";
        String resultx1;
        try {
            //https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcf6d7c834cea0080&secret=665c93355fdfaf7c0c4012b1cec8ad35&grant_type=authorization_code&code=021iACot1iJunb0AGWmt1MbLot1iACoT
            resultx1 = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatAppId + "&secret=" + wechatSecret + "&grant_type=authorization_code&code=" + code, null);
        } catch (Exception e) {
            log.error("error:{}" + e);
//            return new AppBack(-1, "连接微信失败");
            return Result.error(CodeMsg.FAIL);
        }
        if (HttpUtil.checkStart(resultx1)) {
//            return new AppBack(-1, "暂时无法连接微信，请稍后再试");
            return Result.error(CodeMsg.FAIL);
        }

        Map map1 = JSON.parseObject(resultx1, Map.class);

        if (map1.size() == 0) {
//            return new AppBack(-1, "认证失败1");
            return Result.error(CodeMsg.FAIL);
        }
        if (map1.get("openid") == null) {
            log.error("空指针 " + code);
            log.error(JSON.toJSONString(resultx1));
            return Result.error(CodeMsg.FAIL);
//            return new AppBack(-1, "认证失败2");
        }

        String openId = map1.get("openid").toString();
//        String unionid = map1.get("unionid").toString();//为了防止第一次获取不到unionid，第二次请求再获取
        String access_token = map1.get("access_token").toString();
        String resultx;
        try {
            resultx = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo?openid=" + openId + "&access_token=" + access_token, null);
        } catch (Exception e) {
            log.error(String.format("error :{}", e));
            return Result.error(CodeMsg.FAIL);
        }
        Map map = JSON.parseObject(resultx, Map.class);
        if (map.get("openid") == null || map.get("unionid") == null) {
            log.error("空指针 openid" + code);
            log.error(JSON.toJSONString(resultx1));
            return Result.error(CodeMsg.FAIL);
        }
        String unionId = map1.get("unionid").toString();
        WebUser webUser = new WebUser();
        webUser.setOpenid(openId);
        webUser.setUnionId(unionId);
        webUser.setAvatar(map.get("headimgurl").toString());
        return systemUserService.doWechatLogin(webUser, iCode);
    }

}
